import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import * as path from 'path'
import AutoImport from "unplugin-auto-import/vite"
import Components from "unplugin-vue-components/vite"
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import viteCompress from 'vite-plugin-compression'
import vueSetupExtend from 'vite-plugin-vue-setup-extend'

function getConfig (mode: string) {
  if (mode === 'dev') {
    let { configs } = require(`./config/env_dev_config`)
    return configs
  } else if (mode === 'pro') {
    let { configs } = require(`./config/env_pro_config`)
    return configs
  }
}

export default ({ mode }) => {
  let configs = getConfig(mode)

  process.env = { ...process.env, ...configs }
  let processEnv: any = { ...process.env }
  let buildConfig: any = {
    base: processEnv.config_fileBase,
    envDir: './config/',
    envPrefix: 'config_',
    build: {
      outDir: processEnv.config_outDir,
      cssCodeSplit: processEnv.config_cssCodeSplit,
      sourcemap: processEnv.config_sourcemap,
      assetsInlineLimit: processEnv.config_assetsInlineLimit,
      assetsDir: processEnv.config_assetsDir,
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: processEnv.config_dropConsole,
          drop_debugger: processEnv.config_dropDebugger,
          dead_code: processEnv.config_deadCode,
        }
      }
    },
  }
  console.log(processEnv, '环境变量', buildConfig, '构建信息')
  return defineConfig({
    ...buildConfig,
    plugins: [
      vue({
        reactivityTransform: true
      }),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      viteCompress({
        threshold: processEnv.config_threshold,
        filter: processEnv.config_gzipFilter,
        deleteOriginFile: processEnv.config_deleteOriginFile
      }),
      vueSetupExtend()
    ],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
        '@store': path.resolve(__dirname, 'src/store'),
        '@api': path.resolve(__dirname, 'src/api'),
        '@router': path.resolve(__dirname, 'src/router'),
        '@views': path.resolve(__dirname, 'src/views'),
        '@uilts': path.resolve(__dirname, 'src/uilts'),
        '@components': path.resolve(__dirname, 'src/components'),
        '@publicTs': path.resolve(__dirname, 'src/publicTs'),
      }
    }
  })
}

